<!--
author:        hejy <silentmanager@163.com>
date:          2024-11-01 00:09:19
component:     index
Copyright © YourCompanyName All rights reserved
待审核
-->
<template>
  <div>
    <el-card>
      <FormComponent ref="formRef" :config="formConfig">
        <template #submit>
          <div style="margin-left: 24px">
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />重置</el-button>
            <el-popconfirm
              confirm-button-text="通过"
              cancel-button-text="驳回"
              title="请选择审核通过或者拒绝"
              @confirm="handleBatchReview(true)"
              @cancel="handleBatchReview(false)"
              v-hasPermi="['bms:order-info:audit']"
            >
              <template #reference>
                <el-button type="success" v-hasPermi="['bms:order-info:audit']"
                  ><Icon icon="ep:refresh" class="mr-5px" />批量审核</el-button
                >
              </template>
            </el-popconfirm>
          </div>
        </template>
      </FormComponent>
    </el-card>

    <!-- 表格 -->
    <el-card style="margin-top: 24px">
      <el-alert :title="'已选择 ' + selectedCount + ' 项'" type="success" />
      <el-table
        ref="tableRef"
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        :data="list"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="orderNo" />
        <el-table-column label="客户姓名" prop="customerName" />
        <el-table-column label="客户手机号" prop="customerPhone">
          <template #default="{ row }">
            <span>{{ formatPhoneNumber(row.customerPhone) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" prop="address" />
        <el-table-column label="套餐名称" prop="orderPackageName" />
        <el-table-column label="套餐总金额" prop="totalAmount" />
        <el-table-column label="预付款" prop="packagePrepayment" />
        <el-table-column label="录入人" prop="creatorName" />
        <el-table-column label="订单备注" prop="orderNote" />
        <el-table-column label="录单时间" prop="createTime" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <div style="display: flex">
              <el-button
                @click="handleAudit(scope.row.id, true)"
                v-hasPermi="['bms:order-info:audit']"
                link
                type="warning"
                >通过</el-button
              >
              <el-button
                v-hasPermi="['bms:order-info:audit']"
                link
                type="warning"
                @click="handleAudit(scope.row.id, false)"
                >驳回</el-button
              >
              <el-button
                v-hasPermi="['bms:order-waiting-audit:update']"
                link
                type="primary"
                @click="handleEmit(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-hasPermi="['bms:order-info:detail']"
                link
                type="primary"
                @click="viewDetails(scope.row)"
                >详情</el-button
              >
              <el-button
                v-hasPermi="['bms:order-note:create']"
                link
                type="primary"
                @click="showRemarkDialog(scope.row)"
                >备注</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 备注弹窗 -->
    <OrderRemark :remarkId="remarkId" @success="getList" v-model:visible="isRemarkDialogVisible" />
    <!-- 客户详情抽屉 -->
    <OrderDetail
      :orderDetailId="orderDetailId"
      v-model="isDetailDrawerVisible"
      :detailItem="detailItem"
      @success="getList"
    />
    <!-- 编辑弹窗 -->
    <OrderEmit v-model:visible="emitVisible" :emitData="emitData" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { auditOrderInfo, pageOrderInfo, UpdateOrderInfoReq } from '@/api/order/all'
import FormComponent from '@/components/FormComponent/index.vue'
import { pageCustomerUser } from '@/api/customer'
import OrderRemark from '../all/components/orderRemark.vue'
import OrderEmit from '../all/components/orderEmit.vue'
import OrderDetail from '../all/components/orderDetail.vue'
import { CustomerTypeOptions } from '@/mock'
import { defaultProps } from '@/utils/tree'
import { useDeptList } from '@/hooks/useDeptList'
import { defaultTime, formatPhoneNumber } from '@/utils'
import {ElTable} from "element-plus";
const message = useMessage()
function checkAllZeroOrNonZero(numbers: number[]): boolean {
  // 如果全部是 0
  const allZero = numbers.every((num) => num === 0)

  // 如果全部都不是 0
  const allNonZero = numbers.every((num) => num !== 0)

  // 如果满足其中之一则返回 true，否则返回 false
  return allZero || allNonZero
}

const tableRef = ref()
// ----------------------------- 批量审核 -----------------------------
const handleBatchReview = async (status: boolean) => {
  try {
    if (selectedCount.value === 0) {
      message.warning('请至少选择一个订单!')
      return
    }

    const allNoPrepayment = checkAllZeroOrNonZero(selectAllPrepayment.value)
    if (!allNoPrepayment) {
      message.warning('请选择预付款类型相同的订单来进行批量审核!')
      return
    }
    if (status) {
      await message.confirm('确认进行审核批量通过吗')
    } else {
      await message.confirm('确认进行审核批量拒绝吗')
    }
    const res = await auditOrderInfo({ orderIds: selectedIds.value, auditResult: status })
    if (res.code === 0) {
      message.success(status ? '审核通过操作成功' : '审核拒绝操作成功')
      getList()
    }
    // 清空选中项
    tableRef.value.clearSelection()
  } catch (e) {
    console.error(e)
  }
}
// ----------------------------- 通过驳回 -----------------------------
const handleAudit = async (id: number, status: boolean) => {
  try {
    if (status) {
      await message.confirm('确认通过吗')
    } else {
      await message.confirm('确认驳回吗')
    }
    const res = await auditOrderInfo({ orderIds: [id], auditResult: status })
    if (res.code === 0) {
      message.success(status ? '审核通过操作成功' : '审核拒绝操作成功')
      getList()
    }
  } catch (e) {
    console.error(e)
  }
}
// ----------------------------- 编辑弹窗状态 -----------------------------
const emitData = ref<UpdateOrderInfoReq>({
  id: 0,
  customerName: '',
  address: '',
  customerPhone: ''
})
const emitVisible = ref<boolean>(false)
// 显示弹窗的处理函数
const handleEmit = (row) => {
  emitData.value = {
    id: row.id,
    customerName: row.customerName,
    address: row.address,
    customerPhone: row.customerPhone
  }
  emitVisible.value = true
}
// ----------------------------- 备注弹窗状态 -----------------------------
const remarkId = ref(0)
const isRemarkDialogVisible = ref<boolean>(false)
// 显示弹窗的处理函数
const showRemarkDialog = (row) => {
  remarkId.value = row.id
  isRemarkDialogVisible.value = true
}
// ----------------------------- 详情抽屉状态 -----------------------------
const isDetailDrawerVisible = ref(false)
const orderDetailId = ref(0)
const detailItem = ref<pageCustomerUser>()
const viewDetails = (row) => {
  orderDetailId.value = row.id
  isDetailDrawerVisible.value = true
}
// --------------------  表格  ---------------------
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
// 定义选中项数量的状态
const selectedCount = ref(0)
// 选中的id
const selectedIds = ref<number[]>([])
const selectAllPrepayment = ref<number[]>([])
// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})
// 处理选择变化的函数
const handleSelectionChange = (selection: any[]) => {
  selectAllPrepayment.value = selection.map((item) => item.packagePrepayment)
  selectedCount.value = selection.length // 更新选中项的数量
  selectedIds.value = selection.map((item) => item.id)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await pageOrderInfo({
      ...queryParams,
      ...formRef.value?.formData,
      auditTime: formRef.value?.formData.auditTime,
      createTime: formRef.value?.formData.createTime,
      orderStatus: 1
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}
const getRowKey = (row: any) => {
  return row.id
}

/** 初始化 */
onMounted(() => {
  getList()
})
// ==================== 表单  ====================
const formRef = ref<InstanceType<typeof FormComponent>>()
const { deptList } = useDeptList()

const formConfig = ref([
  {
    label: '客户姓名',
    prop: 'customerName',
    type: 'input',
    options: { placeholder: '请输入客户姓名' }
  },
  {
    label: '客户电话',
    prop: 'customerPhone',
    type: 'input',
    options: { placeholder: '请输入客户电话' }
  },
  {
    label: '客户类型',
    prop: 'customerType',
    type: 'select',
    options: {
      placeholder: '请选择客户类型',
      style: 'width: 240px',
      options: CustomerTypeOptions
    }
  },
  {
    label: '订单号',
    prop: 'orderNo',
    type: 'input',
    options: { placeholder: '请输入订单号' }
  },
  {
    label: '运单号',
    prop: 'logisticNo',
    type: 'input',
    options: { placeholder: '请输入运单号' }
  },
  {
    label: '客户地址',
    prop: 'address',
    type: 'input',
    options: { placeholder: '请输入客户地址' }
  },
  {
    label: '商品名称',
    prop: 'orderPackageName',
    type: 'input',
    options: { placeholder: '请输入商品名称' }
  },
  {
    label: '订单总金额',
    prop: 'totalAmount',
    type: 'number',
    options: {
      placeholder: '请输入订单总金额',
      style: { width: '240px' },
      precision: '2',
      min: '0'
    }
  },
  {
    label: '录入人班组',
    prop: 'username',
    type: 'tree',
    options: {
      placeholder: '请选择录入人班组',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '审核时间',
    prop: 'auditTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  },
  {
    label: '录入时间',
    prop: 'createTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  }
])
</script>
